import { createRouter, createWebHashHistory } from 'vue-router'
import SSys from '~/store/SSys'
import System from '~/utils/System'
import privateRoutes from './routes/index'
import SUser from '~/store/SUser'

const routes = [
    ...privateRoutes,
    {
        path: '/:matchOthers(.*)*',
        component: () => import('../views/404/index.vue')
    }
]

const getRouterList = (arr: { path: string; children?: any[] }[], res: Array<string>) => {
    arr.forEach((item) => {
        res.push(item.path)
        if (item.children) res = getRouterList(item.children, res)
    })
    return res
}

System.routerList = getRouterList(JSONUtil.cp(privateRoutes), [])

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    //路由是否存在跳转404
    // router.push("/err")
    let path = to.path
    if (path.indexOf('?') != -1) path = path.split('?')[0]
    if (path !== '/login') {
        const token = SUser.getToken()
        if (StrUtil.isNull(token)) {
            next({ path: '/login' })
            return
        } else {
            if (System.routerList.includes(path)) {
                const menuList = SSys.menuListSource.filter((item) => path === item.url)
                if (menuList.length == 0) {
                    next({ path: '/error' })
                    return
                }
            }
        }
    }
    next()
})

System.router = router
export { router }
